import { login, getInfo, getInfoById } from '@/api/user'
import { getToken, setToken, removeToken, setTokenTime } from '@/utils/auth'
import { resetRouter } from '@/router'
const state = {
  token: getToken(), // 用户token
  userInfo: {}
}

const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
    setTokenTime()
  },
  getUserData(state, payload) {
    state.userInfo = payload
  },
  logout(state) {
    state.token = null
    removeToken()
    state.userInfo = {
      roles: {
        points: [],
        menus: []
      }
    }
    // 重置路由
    resetRouter()
  }
}

const actions = {
  async login(context, data) {
    const res = await login(data)
    // await 下面的代码相当于.then
    context.commit('setToken', res)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const res = await getInfo()
    const userInfoRes = await getInfoById(res.userId)
    res.roles.points.forEach((item, index) => {
      if (typeof item === 'string') {
        res.roles.points[index] = item.toLocaleLowerCase()
      }
    })

    context.commit('getUserData', { ...res, ...userInfoRes })
    return res
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
